<template>
    <div class="noteEditor">
        <!-- 编辑器头部工具栏 -->
        <div class="editorHeader">
            <div class="left-tools">
                <div class="title-wrapper">
                    <span class="title-label">请输入标题</span>
                    <el-input
                        v-model="noteTitle"
                        placeholder="请输入标题"
                        class="titleInput"
                        @change="handleTitleChange"
                    />
                </div>
                <el-dropdown 
                    @command="handleTemplate" 
                    trigger="click"
                    v-if="!isFullscreen"
                >
                    <el-button size="small">
                        <el-icon><Document /></el-icon>
                        模板
                        <el-icon><ArrowDown /></el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu>
                            <el-dropdown-item 
                                v-for="template in templates" 
                                :key="template.id"
                                :command="template.id"
                            >
                                {{ template.name }}
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>
            <div class="right-tools">
                <el-button size="small" type="primary" @click="handleSave">
                    <el-icon><Check /></el-icon>保存
                </el-button>
                <el-button 
                    size="small" 
                    type="danger" 
                    @click="handleDelete"
                    v-if="!isFullscreen"
                >
                    <el-icon><Delete /></el-icon>删除
                </el-button>
                <el-button size="small" @click="toggleFullscreen">
                    <el-icon><FullScreen /></el-icon>
                    {{ isFullscreen ? '退出全屏' : '全屏' }}
                </el-button>
            </div>
        </div>

        <div class="editorContent">
            <!-- Markdown编辑器 -->
            <div class="editor-section" :style="{ width: editorWidth + '%' }">
                <el-input
                    v-model="markdownContent"
                    type="textarea"
                    placeholder="开始写作..."
                    resize="none"
                    @input="handleContentChange"
                />
            </div>
            
            <!-- 拖动动条 -->
            <div 
                class="resize-handle"
                @mousedown="startResize"
            ></div>
            
            <!-- 预览区 -->
            <div 
                class="previewArea" 
                v-html="renderedContent"
                :style="{ width: (100 - editorWidth) + '%' }"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, onUnmounted, onMounted } from 'vue';
import { useNoteStore } from '@/store/modules/note/noteStore';
import { Document, Check, FullScreen, ArrowDown, Delete } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import MarkdownIt from 'markdown-it';
import 'github-markdown-css';

const noteStore = useNoteStore();
const templates = computed(() => Object.values(noteStore.templates));

// 添加保存和模板应用方法
const handleTemplate = (templateId: string) => {
    const template = noteStore.applyTemplate(templateId);
    if (template) {
        noteTitle.value = template.title;
        markdownContent.value = template.content;
        renderedContent.value = md.render(template.content);
        
        // 触发更新事件
        emit('titleChange', template.title);
        emit('change', template.content);
        handleSave();
        ElMessage.success('已应用模板');
    }
};

// 删除 defineProps 的导入，直接使用
const props = defineProps<{
    modelValue: string;
    title: string;
}>();

// Emits 定义
const emit = defineEmits<{
    'save': [];
    'delete': [];
    'update:modelValue': [value: string];
    'change': [content: string];
    'titleChange': [title: string];
}>();

const md = new MarkdownIt({
    html: true,
    breaks: true,
    linkify: true,
    typographer: true
});

// 添加自定义换行规则
md.renderer.rules.softbreak = () => '<br>\n';
md.renderer.rules.hardbreak = () => '<br>\n';

const noteTitle = ref('');
const markdownContent = ref('');
const isPreview = ref(false);
const isFullscreen = ref(false);
const renderedContent = ref('');

// 添加拖动相关的响应式变量和方法
const editorWidth = ref(50); // 初始编辑器宽度为40%
let isResizing = false;

const startResize = (e: MouseEvent) => {
    isResizing = true;
    document.addEventListener('mousemove', handleResize);
    document.addEventListener('mouseup', stopResize);
};

const handleResize = (e: MouseEvent) => {
    if (!isResizing) return;
    
    const container = document.querySelector('.editorContent');
    if (!container) return;
    
    // 使用 requestAnimationFrame 优化性能
    requestAnimationFrame(() => {
        const containerRect = container.getBoundingClientRect();
        const newWidth = ((e.clientX - containerRect.left) / containerRect.width) * 100;
        
        // 添加缓动效果
        const currentWidth = editorWidth.value;
        const diff = newWidth - currentWidth;
        const smoothedWidth = currentWidth + (diff * 0.2);
        
        // 限制范围并保留一位小数
        editorWidth.value = Math.min(Math.max(parseFloat(smoothedWidth.toFixed(1)), 30), 70);
    });
};

const stopResize = () => {
    isResizing = false;
    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', stopResize);
};

// 添加防止文本选择的处理
const preventSelect = (e: Event) => {
    if (isResizing) {
        e.preventDefault();
    }
};

onMounted(() => {
    document.addEventListener('selectstart', preventSelect);
});

onUnmounted(() => {
    document.removeEventListener('selectstart', preventSelect);
    document.removeEventListener('mousemove', handleResize);
    document.removeEventListener('mouseup', stopResize);
});

// 监听 props 变化
watch(() => props.title, (newValue) => {
    noteTitle.value = newValue || '新建笔记';
}, { immediate: true });

watch(() => props.modelValue, (newValue) => {
    markdownContent.value = newValue || '';
    renderedContent.value = md.render(newValue || '');
}, { immediate: true });

// 处理标题变化
const handleTitleChange = () => {
    emit('titleChange', noteTitle.value);
};

// 处理内容变化
const handleContentChange = () => {
    emit('update:modelValue', markdownContent.value);
    emit('change', markdownContent.value);
};

// 切换预览模式
// const togglePreview = () => {
//     isPreview.value = !isPreview.value;
//     if (isPreview.value) {
//         renderedContent.value = md.render(markdownContent.value);
//     }
// };

// 切换全屏模式
const toggleFullscreen = () => {
    isFullscreen.value = !isFullscreen.value;
    const editor = document.querySelector('.noteEditor');
    if (isFullscreen.value) {
        editor?.requestFullscreen();
    } else {
        document.exitFullscreen();
    }
};

// 处理保存
const handleSave = () => {
    emit('save');
};

// 处理删除
const handleDelete = () => {
    emit('delete');
};

// 添加样式类控制
const resizeHandleClass = computed(() => ({
    'resize-handle': true,
    'is-resizing': isResizing
}));
</script>

<style scoped>
.noteEditor {
    height: 100%;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.editorHeader {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.left-tools {
    display: flex;
    gap: 10px;
    align-items: center;
    flex: 1;
}

.right-tools {
    display: flex;
    gap: 10px;
    align-items: center;
}

.title-wrapper {
    display: flex;
    align-items: center;
    gap: 8px;
    max-width: 400px;
}

.title-label {
    color: #606266;
    font-size: 14px;
    white-space: nowrap;
}

.titleInput {
    flex: 1;
}

.titleInput :deep(.el-input__wrapper) {
    background-color: transparent;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    transition: all 0.3s;
    padding: 0 12px;
}

.titleInput :deep(.el-input__wrapper):hover,
.titleInput :deep(.el-input__wrapper):focus {
    border-color: #409EFF;
    box-shadow: 0 0 0 1px #409EFF;
}

.editorContent {
    flex: 1;
    display: flex;
    padding: 20px;
    height: calc(100% - 60px);
    min-height: 0;
    position: relative;
    overflow: hidden;
    border: 1px solid #ebeef5;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    transition: box-shadow 0.3s ease;
    margin: 0 auto 20px;
    width: 100%;
    margin-bottom: 5%;
    margin-top: 5%;
    user-select: none;
}

.editor-section {
    height: 100%;
    transition: width 0.1s cubic-bezier(0.4, 0, 0.2, 1);
    display: flex;
    overflow: hidden;
    border-radius: 8px;
    margin: 0 10px;
    /* width: 50%; */
    width: 100%;
}

.editor-section :deep(.el-input) {
    height: 100%;
    width: 100% !important;
    flex: 1;
}

:deep(.el-textarea__inner) {
    height: 100% !important;
    font-family: 'Consolas', monospace;
    resize: none;
    padding: 20px;
    border-radius: 8px;
    overflow-y: auto;
    background-color: transparent;
    border: none;
    box-shadow: none;
    color: #303133;
    scrollbar-width: none;
    -ms-overflow-style: none;
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-wrap: break-word;
    line-height: 1.6;
}

.editor-section :deep(.el-textarea__inner)::-webkit-scrollbar {
    display: none;
}

.resize-handle {
    width: 6px;
    background-color: #dcdfe6;
    cursor: col-resize;
    transition: background-color 0.2s, transform 0.2s;
    margin: 0 10px;
    position: relative;
}

.resize-handle:hover {
    transform: scaleX(1.5);
    background-color: #409eff;
}

.resize-handle.is-resizing {
    transform: scaleX(2);
    background-color: #409eff;
}

.resize-handle::after {
    content: '';
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 2px;
    height: 20px;
    background-color: #fff;
    border-radius: 1px;
}

.previewArea {
    /* width: 60% !important; */
    height: 100%;
    /* background-color: #ff0000; */
    padding: 30px;
    overflow-y: auto;
    /* border: 1px solid #ebeef5; */
    border-radius: 8px;
    scrollbar-width: none;
    -ms-overflow-style: none;
    word-wrap: break-word;
    overflow-x: hidden;
    margin: 0 10px;
    font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Helvetica, Arial, sans-serif;
    line-height: 1.6;
    width: 100%;
    overflow-wrap: break-word;
    padding-bottom: 40px;
    box-sizing: border-box;
    height: 100%;
    /* overflow: hidden; */
    background-color: #ff000000;
    transition: width 0.1s cubic-bezier(0.4, 0, 0.2, 1);
}

/* Markdown 内容样式 */
.previewArea :deep(p) {
    margin: 1em 0;
    /* white-space: pre-wrap; */
}

.previewArea :deep(br) {
    display: block;
    content: "";
    margin: 0.5em 0;
}

.previewArea :deep(pre) {
    white-space: pre-wrap;
    word-wrap: break-word;
    overflow-x: auto;
    padding: 1em;
    background-color: #f6f8fa;
    border-radius: 6px;
    margin: 1em 0;
}

.previewArea :deep(code) {
    font-family: 'Consolas', monospace;
    padding: 0.2em 0.4em;
    background-color: #f6f8fa;
    border-radius: 3px;
}

.previewArea :deep(blockquote) {
    margin: 1em 0;
    padding: 0 1em;
    color: #6a737d;
    border-left: 0.25em solid #dfe2e5;
}

/* 全屏模式下的文字颜色 */
.noteEditor:fullscreen .editor-section :deep(.el-textarea__inner),
.noteEditor:fullscreen .previewArea {
    color: #ffffff;
}

.noteEditor:fullscreen .markdown-body {
    color: #ffffff;
}

.noteEditor:fullscreen .title-label{
    color: #ffffff;
}

.noteEditor:fullscreen .markdown-body h1,
.noteEditor:fullscreen .markdown-body h2,
.noteEditor:fullscreen .markdown-body h3,
.noteEditor:fullscreen .markdown-body h4,
.noteEditor:fullscreen .markdown-body h5,
.noteEditor:fullscreen .markdown-body h6,
.noteEditor:fullscreen .markdown-body p,
.noteEditor:fullscreen .markdown-body li {
    color: #ffffff;
}

.noteEditor:fullscreen .markdown-body code {
    color: #d4d4d4;
    background-color: #1e1e1e;
}

.noteEditor:fullscreen .markdown-body pre {
    background-color: #1e1e1e;
}

</style>
